#pragma once
#include <signal.h>
#include "TcpServer.hpp"
#include "Task.hpp"
#include "ThreadPool.hpp"

#define PORT 8000

class HttpServer
{
public:
    HttpServer(int port = PORT)
        :_port(port),
         //_tpc_server(nullptr),
         _stop(false)
    {}

    void InitServer()
    {
        // 信号忽略，不然写入时可能直接崩溃
        signal(SIGPIPE, SIG_IGN);
        //_tpc_server = TcpServer::GetInstance(_port);
    }

    void Loop()
    {
        //int listen_sock = _tpc_server->Sock();
        TcpServer *tsvr = TcpServer::GetInstance(_port);
        while (!_stop)
        {
            struct sockaddr_in peer;
            memset(&peer, 0, sizeof(peer));
            socklen_t len = sizeof(peer);

            int sock = accept(tsvr->Sock(), (sockaddr *)&peer, &len);
            if (sock < 0)
            {
                continue;
            }

            LOG(INFO, "get a new link...");
            // int* tmp_sock = new int(sock);
            // pthread_t tid;
            // pthread_create(&tid, nullptr, Entrance::HandlerRequest, tmp_sock);

            // 引入线程池
            Task task(sock);
            ThreadPool::GetInstance()->PushTask(task);
            //_pool.push_back(task);
        }
    }

    ~HttpServer()
    {}

private:
    int _port;
    //TcpServer* _tpc_server;
    bool _stop;
};